package com.example.annotation;


import com.example.configDataSource.DynamicDataSourceHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * step5:注解拦截器器拦截所有的service，根据注解设置当前线程将使用的是哪个数据源
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Around("@annotation(com.example.annotation.TargetDataSource)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
      MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
      Method targetMethod = methodSignature.getMethod();
      if (targetMethod.isAnnotationPresent(TargetDataSource.class)) {
        String targetDataSource = targetMethod.getAnnotation(TargetDataSource.class).value();
        System.out.println("----------数据源是:" + targetDataSource + "------");
        /*设置线程与当前数据源绑定*/
        DynamicDataSourceHolder.setDataSource(targetDataSource);
      }
      Object result = pjp.proceed();//执行方法
      DynamicDataSourceHolder.clearDataSource();
      return result;
    }
  }